package com.cong.nio.echo;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class NioServer {
    public static void main(String[] args) throws IOException {
        Selector selector = Selector.open();
        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        socketChannel.configureBlocking(false);
        socketChannel.register(selector, SelectionKey.OP_ACCEPT);

        ServerSocket serverSocket = socketChannel.socket();
        InetSocketAddress address = new InetSocketAddress(8888);
        serverSocket.bind(address);

        while (true){
            selector.select();
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
            while (keyIterator.hasNext()){
                SelectionKey key = keyIterator.next();

                if (key.isAcceptable()){
                    ServerSocketChannel channel = (ServerSocketChannel)key.channel();
                    SocketChannel socketChannel1 = channel.accept();
                    socketChannel1.configureBlocking(false);
                    socketChannel1.register(selector,SelectionKey.OP_READ);
                }else if (key.isReadable()){
                    SocketChannel socketChannel1 = (SocketChannel) key.channel();
                    System.out.println(readDataFromSocketChannel(socketChannel1));
                    socketChannel1.close();
                }
                keyIterator.remove();
            }
        }
    }

    private static String readDataFromSocketChannel(SocketChannel channel) throws IOException {
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        StringBuilder stringBuilder = new StringBuilder();
        while (true){
            buffer.clear();
            int read = channel.read(buffer);
            if (read==-1){
                break;
            }
            buffer.flip();
            int limit = buffer.limit();
            char[] dst = new char[limit];
            for (int i = 0; i <limit ; i++) {
                dst[i] =(char) buffer.get(i);
            }
            stringBuilder.append(dst);
            buffer.clear();

        }
        return stringBuilder.toString();

    }
}
